package org.devocean.groupbuying.web.frontend;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.devocean.groupbuying.domain.Customer;
import org.devocean.groupbuying.service.CustomerService;
import org.devocean.groupbuying.service.PaypalPaymentService;
import org.devocean.groupbuying.web.frontend.displaybeans.PurchaseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
// /customers/payment/paypal/
@RequestMapping(value = { "/customers/payment/paypal/" })
public class PayPalController {

	@Autowired
	private PaypalPaymentService paypalPaymentService;
	
	@Autowired
	private CustomerService customerService;
	
	@Value("#{Credit['credit']}")
	private Double credit;

	@RequestMapping(value = "checkout", method = RequestMethod.GET)
	public String setCheckout(ModelMap modelMap, Principal principal) {

		final Integer customerID = Integer.valueOf(principal.getName());
		String retunView;

		try {
			// valid purchase
			paypalPaymentService.validPurchase(customerID);
			retunView = "redirect:" + paypalPaymentService.setCheckout();
		} catch (Exception e) {
			modelMap.addAttribute("msg", e.getMessage()); // DevMode Only
			retunView = "error";
		}
		return retunView;
	}

	@RequestMapping(value = "doChekOut/{action}")
	public String docheckout(@RequestParam("token") String token,
			@RequestParam("PayerID") String payerID, ModelMap modelMap,
			Principal principal, @PathVariable("action") String action,HttpServletRequest request) {

		final Integer customerID = Integer.valueOf(principal.getName());
		String retunView;

		try {

			PurchaseBean purchaseBean = new PurchaseBean(
					paypalPaymentService.doCheckOutPayment(customerID, payerID,
							token, action));
			modelMap.addAttribute("purchaseBean", purchaseBean);
			if (request.getSession().getAttribute("customerUuid")!=null) {
				String uuid = request.getSession().getAttribute("customerUuid").toString();
				Customer customer = customerService.getCustomerByUuid(uuid);
				customer.setCredit(customer.getCredit()+credit);
				customerService.addOrUpdateCustomer(customer);
			}
			
			retunView = "payment/payed";

		} catch (Exception e) {
			e.printStackTrace();
			modelMap.addAttribute("msg", e.getMessage()); // DevMode Only
			retunView = "error";
		}

		return retunView;
	}
}
